package com.nenglai.admin.modular.system.controller;

import com.alibaba.druid.util.Base64;
import com.google.code.kaptcha.Producer;
import com.nenglai.admin.modular.system.form.LoginForm;
import com.nenglai.admin.modular.system.form.RegisterForm;
import com.nenglai.admin.modular.system.form.ResetPasswordForm;
import com.nenglai.admin.modular.system.service.ReportAdminService;
import com.nenglai.admin.modular.system.vo.AdminVO;
import com.nenglai.admin.modular.system.vo.CaptchaVO;
import com.nenglai.admin.modular.system.vo.LoginVO;
import com.nenglai.common.captcha.CaptchaException;
import com.nenglai.common.captcha.CaptchaHelper;
import com.nenglai.common.jwt.TokenUtil;
import com.nenglai.common.response.ErrorCode;
import com.nenglai.common.response.ResponseException;
import com.nenglai.common.response.Result;
import com.nenglai.common.response.ResultGenerator;
import com.nenglai.model.system.entity.Admin;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("backend/admin")
public class AdminController {

    /**
     * AdminService
     */
    private final ReportAdminService adminService;
    /**
     * 验证码生成器
     */
    private final Producer kaptchaProducer;
    /**
     * 待验证管理器
     */
    private final CaptchaHelper captchaHelper;

    public AdminController(ReportAdminService adminService, Producer kaptchaProducer,
                           @Qualifier("login") CaptchaHelper captchaHelper) {
        this.adminService = adminService;
        this.kaptchaProducer = kaptchaProducer;
        this.captchaHelper = captchaHelper;
    }

    /**
     * 验证码
     * 
     * @author kongdehui
     * @date 2021/04/24 09:19
     * @return com.xiaositea.admin.response.Result<?>
     */
    @PostMapping("kaptcha")
    public Result<?> captcha() {
        String capText = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(capText);
        ByteArrayOutputStream bs = null;
        try {
            bs = new ByteArrayOutputStream();
            ImageIO.write(image, "png", bs);// 将绘制得图片输出到流
            String base64 = Base64.byteArrayToBase64(bs.toByteArray());
            String token = captchaHelper.key();
            captchaHelper.addElement(token, capText.toLowerCase());
            return ResultGenerator.success(CaptchaVO.builder().token(token).base64(base64).build());
        } catch (IOException e) {
            e.printStackTrace();
            return ResultGenerator.error(ErrorCode.CAPTCHA_GENERATOR_FAIL);
        } finally {
            try {
                assert bs != null;
                bs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 登录系统
     * 
     * @author kongdehui
     * @date 2021/04/21 15:14
     * @param loginForm
     * @return com.xiaositea.admin.response.Result<com.xiaositea.admin.modular.system.vo.LoginVO>
     */
    @PostMapping("login")
    public Result<?> login(@Valid @RequestBody LoginForm loginForm) {
        try {
            if (!captchaHelper.verifyOnce(loginForm.getToken(), loginForm.getCode().toLowerCase())) {
                return ResultGenerator.error("验证码不正确");
            }
        } catch (CaptchaException e) {
            e.printStackTrace();
            return ResultGenerator.error(e.getMessage());
        }

        Admin admin = adminService.login(loginForm);
        if (admin == null) {
            throw new ResponseException(ErrorCode.LOGIN_FAIL);
        }
        String token = TokenUtil.getToken(admin.getId(), admin.getPassword());
        AdminVO adminVO = AdminVO.builder().id(admin.getId()).phone(admin.getPhone()).username(admin.getUsername())
            .type(admin.getType()).status(admin.getStatus()).build();
        return ResultGenerator.success(LoginVO.builder().token(token).user(adminVO).build());
    }

    /**
     * 注册管理员
     * 
     * @author kongdehui
     * @date 2021/04/21 22:06
     * @param registerForm
     * @return com.xiaositea.admin.response.Result<java.lang.String>
     */
    @PostMapping("register")
    public Result<String> register(@RequestBody RegisterForm registerForm) {
        boolean save = adminService.register(registerForm);
        return ResultGenerator.successOrError(save, "注册成功", "注册失败");
    }

    /**
     * 重置密码
     * 
     * @author kongdehui
     * @date 2021/05/01 13:59
     * @param form
     * @return com.xiaositea.admin.response.Result<java.lang.String>
     */
    @PostMapping("reset-password")
    public Result<String> resetPassword(@Valid @RequestBody ResetPasswordForm form) {
        boolean reset = adminService.resetPassword(form);
        return ResultGenerator.successOrError(reset, "重置成功", "重置失败");
    }
}
